package com.zhaotianhao.controller;

import com.github.pagehelper.PageInfo;
import com.zhaotianhao.pojo.Goods;
import com.zhaotianhao.service.GoodsService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author Z-7
 * @Date 2022/3/3
 */
@Controller
@RequestMapping("goods")
public class GoodsController {
    @DubboReference
    private GoodsService goodsService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 预热 --- 缓存首页内容
     * 缓存时间  10分钟
     */
    @PostConstruct
    public void preheat(){
        PageInfo<Goods> home = (PageInfo<Goods>) redisTemplate.opsForValue().get("home");
        if(home == null){
            home = goodsService.queryByPage(null, 1, 3);
            redisTemplate.opsForValue().set("home",home,10, TimeUnit.MINUTES);
        }
    }
    @RequestMapping("list")
    public String to_list(@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "3")int pageSize, Model model){
        PageInfo<Goods> page = (PageInfo<Goods>) redisTemplate.opsForValue().get("home");
        if(page == null ){
            page = goodsService.queryByPage(null, pageNum, pageSize);
            redisTemplate.opsForValue().set("home",page,10, TimeUnit.MINUTES);
        }
        page.getList().stream().forEach(System.out::println);
        model.addAttribute("page",page);
        return "index";
    }
}
